import { useEffect, useState, useCallback } from 'react';
import { fetchUserSessions, createSession, deleteSession, pinSession } from '../services/api';

export default function SessionSidebar({ userId = '2000', activeSessionId, onSelect }) {
  const [sessions, setSessions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [newName, setNewName] = useState('默认会话');

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await fetchUserSessions(userId);
      const list = (data.sessions || []).slice().sort((a, b) => {
        if (a.pinned !== b.pinned) return b.pinned ? 1 : -1; // pinned 优先
        const getTime = (x) => new Date(x.lastActiveAt || x.createdAt || 0).getTime();
        return getTime(b) - getTime(a); // 最近活跃优先
      });
      setSessions(list);
      // 自动选择：若未选择或当前选择不存在，则选中最新一个
      const currentExists = list.some(s => s.sessionId === activeSessionId);
      if ((!activeSessionId || !currentExists) && list.length > 0) {
        onSelect?.(list[0].sessionId);
      }
    } catch (e) {
      console.error(e);
      alert('加载会话失败');
    } finally {
      setLoading(false);
    }
  }, [userId, activeSessionId, onSelect]);

  useEffect(() => {
    load();
  }, [load]);

  const handleCreate = async () => {
    if (!newName.trim()) return;
    try {
      const created = await createSession({ userId, sessionName: newName.trim(), sessionType: 'general' });
      setNewName('默认会话');
      await load();
      if (created?.sessionId) {
        onSelect?.(created.sessionId);
      }
    } catch (e) {
      console.error(e);
      alert('创建会话失败');
    }
  };

  const handleDelete = async (sessionId) => {
    if (!confirm('确认删除该会话？')) return;
    try {
      await deleteSession(sessionId, userId);
      if (activeSessionId === sessionId) onSelect?.(undefined);
      await load();
    } catch (e) {
      console.error(e);
      alert('删除会话失败');
    }
  };

  const handlePin = async (sessionId, pinned) => {
    try {
      await pinSession(sessionId, !pinned);
      await load();
    } catch (e) {
      console.error(e);
      alert('置顶失败');
    }
  };

  return (
    <div className="session-sidebar">
      <div className="session-header">会话</div>
      <div className="session-create">
        <input
          className="session-input"
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          placeholder="会话名称"
        />
        <button className="session-create-btn" onClick={handleCreate} disabled={loading}>新建</button>
      </div>
      <div className="session-list">
        {loading && <div className="session-empty">加载中...</div>}
        {!loading && sessions.length === 0 && <div className="session-empty">暂无会话</div>}
        {sessions.map((s) => (
          <div
            key={s.sessionId}
            className={`session-item ${activeSessionId === s.sessionId ? 'active' : ''}`}
            onClick={() => onSelect?.(s.sessionId)}
          >
            <div className="session-title">
              {s.pinned && <span className="pin">📌</span>}
              <span className="name">{s.sessionName}</span>
            </div>
            <div className="session-actions" onClick={(e) => e.stopPropagation()}>
              <button className="link" onClick={() => handlePin(s.sessionId, s.pinned)}>{s.pinned ? '取消置顶' : '置顶'}</button>
              <button className="danger" onClick={() => handleDelete(s.sessionId)}>删除</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
